import { isLogin, toLogin, getUserInfo, setUserInfo } from '../../utils/auth'
import area from '../../utils/area';
import { checkPhone } from "../../utils/validate";
import ValidateForm from "../../utils/validateForm";
import { showModel, showNotify, showToast, showDialog } from '../../utils/index'
import http from '../../utils/http'
import { handleOpenIdBindingToMobile, requestPayment } from '../../utils/wx'


Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 微信授权，绑定openid
        show: false,

        showPopup: false,

        // 支付方式
        checkedPayWay: 'wechat',
        address: null,
        userInfo: null,
        orderInfo: null,
        discountAmount: 0,
        couponAmount: 0,
        note: null,

        freightType: '',

        dataListMemberCoupon: [],

        result: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 获取传递过来需购买的商品数据
        let { data } = options
        data = JSON.parse(data)
        this.setData({ goods: data.goods })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 用户登录信息
        this.setData({ userInfo: getUserInfo() });

        // 获取缓存中的地址
        const address = wx.getStorageSync('address') || {};
        // 将数据重新设置会data和缓存中
        this.setData({ address });

        this.getGoodsLists()

        this.getDataListMemberCoupon()
    },

    goPage(e) {
        const { url } = e.currentTarget.dataset
        if (!isLogin()) return toLogin()
        wx.navigateTo({ url });
    },

    /**
     * 选择优惠券
     * @returns 
     */
    showPopupFun() {
        this.setData({ showPopup: true })
    },
    onClose() {
        this.setData({ showPopup: false });
    },

    /**
     * 购物车商品选中
     * @param {*} e 
     */
     onChangeChecked(e) {
        this.setData({
            result: e.detail,
        });
        // 优惠券金额
        let coupontAmount = 0
        this.data.result.forEach(item => {
            console.log(this.data.dataListMemberCoupon[item]);
            coupontAmount += this.data.dataListMemberCoupon[item].umsCoupon.amount
        })
        console.log('优惠券金额', coupontAmount);
    },

    /**
     * 获取我的优惠券
     */
     async getDataListMemberCoupon() {
        let { userInfo } = this.data
        let res = await http.get('/api/mall/umsmember/getUserCoupons/'+userInfo.id)
        if (res.status) {
            this.setData({ dataListMemberCoupon: res.data })
        }
    },

    /**
     * 获取下单商品计算价格并确认订单
     */
     async getGoodsLists() {
        const { userInfo, goods } = this.data
        
        let data = {
            memberId: userInfo.id,
            items: goods
        }
        let res = await http.post('/api/mall/omsorder/confirmOrder', data)
        if(res.status) {
            let discountAmount = (res.data.originPrice - res.data.payPrice).toFixed(2)
            
            let freightType = ''
            console.log(userInfo);
            if(userInfo.level.level == 1) {
                freightType = '到付'
            }
            if(userInfo.level.level == 2 && res.data.originPrice >= 5000) {
                freightType = '包邮'
            } else {
                freightType = '到付'
            }
            if(userInfo.level.level == 3) {
                freightType = '包邮'
            }
            if(userInfo.level.level == 4) {
                freightType = '到付'
            }

            this.setData({ orderInfo: res.data, discountAmount, freightType  })
        }
    },

    async submitOrder() {
        const { orderInfo, address, note, freightType } = this.data
        const { APPID, userInfo } = getApp().globalData

        if(!userInfo.openid) {
            this.setData({ show: true }); return false;
        }

        if(!address.contact || !address.phone) {
            showToast({title: '请填写收件地址'}); return false;
        }

        wx.showLoading({ title: '正在加载中'})

        // 构建订单商品
        let orderGoodSku = []
        orderInfo.items.forEach(v => orderGoodSku.push({
            skuId: v.skuId,     // 商品ID
            skuNum: v.count     // 商品数量
        }))
        console.log('构建订单商品==>', orderGoodSku);
        
        // 构建订单数据
        let orderParams = {
            appId: APPID,
            agentId: userInfo.agentId,
            openId: userInfo.openid,
            memberId: userInfo.id,
            memberUsername: userInfo.nickname,
            memberPhone: userInfo.mobile,
            totalAmount: orderInfo.total,               // 订单总额
            payAmount: orderInfo.payPrice,              // 应付金额（实际支付金额）
            freightAmount: orderInfo.shippingPrice,     // 运费
            orderType: 0,   // 订单类型
            payType: 1,
            deliverType: 0,
            receiverName: address.contact,
            receiverPhone: address.phone,
            receiverProvince: address.province,
            receiverCity: address.city,
            receiverRegion: address.district,
            receiverDetailAddress: address.address,
            note: note,
            skus: orderGoodSku,
            freightType
        }
        console.log('构建订单数据==>', orderParams);

        // 发送请求 创建订单 获取订单编号
        const res = await http.post('/api/mall/omsorder/submitOrder', orderParams).catch(function(err) {
            console.log(err);
        })
        console.log('发送请求 创建订单 获取订单编号', res);

        if (res.status) {
            let order = res.data
            // 订单编号
            const orderSn = order.orderSn
            if (orderSn) {
                // 微信订单预支付请求体参数
                const orderPayParams = {
                    appid: APPID,
                    openid: userInfo.openid,
                    outTradeNo: orderSn,
                    body: '[保美驰]商品支付',
                    totalFee: res.data.payAmount * 100
                }

                console.log(orderPayParams);

                // 发起 预支付接口
                http.post(`/api/wx/order/pay/${APPID}/now`, orderPayParams).then(res => {
                    if (res.status) {
                        wx.hideLoading()
                        // 发起 微信支付
                        requestPayment(res.data).then(res => {
                            const { errMsg } = res
                            if (errMsg === 'requestPayment:ok') {
                                console.log(res);
                                // 跳转到支付成功页面
                                let pay_result = {
                                    orderSn: orderSn,
                                    payTime: order.utime,
                                    payWayText: '微信支付',
                                    payAmount: order.payAmount
                                }
                                wx.reLaunch({
                                    url: '/pages/order_pay_result/order_pay_result?data='+JSON.stringify(pay_result)
                                });
                            } else {
                                wx.hideLoading()
                                console.log('订单支付失败[' + errMsg + ']');
                            }
                        }).catch(function(err) {
                            wx.hideLoading()
                            console.log('调起微信支付失败：', err);

                            if (err.errMsg === 'requestPayment:fail cancel') {
                                console.log('用户取消支付');
                            }
                            if (err.errMsg === 'requestPayment:fail no permission') {
                                console.log('title: 未开通支付权限[' + err.errMsg + ']');
                            }
                        })

                    } else {
                        wx.hideLoading()
                        console.log('发起微信支付', res.msg);
                    }
                })
            }
        } else {
            wx.hideLoading()
            console.log(res.msg);
            showToast({title: res.msg})
        }

    },

    /**
     * 支付方式
     * @param {*} e 
     */
    onChangePayWay(e) {
        this.setData({ checkedPayWay: e.detail });
    },

    /**
     * 微信支付需会员与openid绑定
     * @param {*} e 
     */
     async getUserInfo(e) {
        const userInfo = await handleOpenIdBindingToMobile(e);
        if (userInfo) {
            if(userInfo.openid) {
                showToast({title: '会员与openid绑定：成功'}); return false;
            }
        } else {
            console.log('会员与openid绑定：失败');
            this.setData({ show: true })
        }
    },

    onCancel() {
        this.setData({ show: false });
    },
})